package com.hooper.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hooper.project.common.ErrorCode;
import com.hooper.project.exception.BusinessException;
import com.hooper.project.mapper.UserInterfaceInfoMapper;
import com.hooper.project.model.entity.UserInterfaceInfo;
import com.hooper.project.service.UserInterfaceInfoService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;

/**
 * @author Mind
 * @description 针对表【user_interface_info(用户接口信息关系表)】的数据库操作Service实现
 * @createDate 2023-04-12 22:39:48
 */
@Service
public class UserInterfaceInfoServiceImpl extends ServiceImpl<UserInterfaceInfoMapper, UserInterfaceInfo>
        implements UserInterfaceInfoService {


    @Override
    public boolean callInterface(Long interfaceInfoId, Long userId) {
        if (ObjectUtils.anyNull(interfaceInfoId, userId)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (interfaceInfoId <= 0 || userId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 查询用户是否有该接口的调用权限
        LambdaQueryWrapper<UserInterfaceInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserInterfaceInfo::getInterfaceInfoId, interfaceInfoId);
        wrapper.eq(UserInterfaceInfo::getUserId, userId);
        UserInterfaceInfo userInterfaceInfo = this.getOne(wrapper);
        if (userInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "无该接口的调用权限");
        }
        // 判断是否有调用次数
        if (userInterfaceInfo.getLeftNum() <= 0) {
            throw new BusinessException(ErrorCode.NO_CALL_COUNT_AVAILABLE);
        }
        // 调用次数减一
        userInterfaceInfo.setLeftNum(userInterfaceInfo.getLeftNum() - 1);
        // 总调用次数加一
        userInterfaceInfo.setTotalNum(userInterfaceInfo.getTotalNum() + 1);
        // 更新
        this.updateById(userInterfaceInfo);
        return true;
    }

    @Override
    public void validUserInterfaceInfo(UserInterfaceInfo userInterfaceInfoEntity, boolean add) {
        if (userInterfaceInfoEntity == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (add) {
            if (userInterfaceInfoEntity.getUserId() <= 0 || userInterfaceInfoEntity.getInterfaceInfoId() <= 0) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户id或接口id不存在");
            }
        }
        if (userInterfaceInfoEntity.getLeftNum() < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "剩余次数不能小于0");
        }
    }
}




